# exerc2.py
import os
import requests


def download_image():
    # 图片URL
    image_url = "http://n.sinaimg.cn/news/crawl/117/w550h367/20220417/a3a9-08b2ca6dffe4210149dda424adf0734f.jpg"

    # 获取桌面路径
    desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')

    # 图片保存路径
    save_path = os.path.join(desktop_path, 'downloaded_image.jpg')

    try:
        # 下载图片
        response = requests.get(image_url, stream=True)
        response.raise_for_status()  # 检查请求是否成功

        # 保存图片到桌面
        with open(save_path, 'wb') as file:
            for chunk in response.iter_content(1024):
                file.write(chunk)

        print(f"图片已成功下载并保存到: {save_path}")

    except requests.exceptions.RequestException as e:
        print(f"下载图片时出错: {e}")
    except IOError as e:
        print(f"保存文件时出错: {e}")


if __name__ == "__main__":
    download_image()